#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dictionary.h"

// 哈希函数
unsigned int hash(const char *key) {
    unsigned int hash = 0;
    while (*key) {
        hash = (hash << 5) + *key++;
    }
    return hash % TABLE_SIZE;
}

// 创建字典
struct Dictionary* createDictionary() {
    struct Dictionary *dict = (struct Dictionary*) malloc(sizeof(struct Dictionary));
    for (int i = 0; i < TABLE_SIZE; i++) {
        dict->table[i] = NULL;
    }
    return dict;
}

// 插入键值对
void insert(struct Dictionary *dict, const char *key, const char *value) {
    unsigned int index = hash(key);
    struct DictItem *newItem = (struct DictItem*) malloc(sizeof(struct DictItem));
    newItem->key = strdup(key);
    newItem->value = strdup(value);
    newItem->next = dict->table[index];
    dict->table[index] = newItem;
}

// 查找值
char* search(struct Dictionary *dict, const char *key) {
    unsigned int index = hash(key);
    struct DictItem *item = dict->table[index];
    while (item) {
        if (strcmp(item->key, key) == 0) {
            return item->value;
        }
        item = item->next;
    }
    return NULL;
}

// 删除键值对
void delete(struct Dictionary *dict, const char *key) {
    unsigned int index = hash(key);
    struct DictItem *item = dict->table[index];
    struct DictItem *prev = NULL;
    while (item) {
        if (strcmp(item->key, key) == 0) {
            if (prev) {
                prev->next = item->next;
            } else {
                dict->table[index] = item->next;
            }
            free(item->key);
            free(item->value);
            free(item);
            return;
        }
        prev = item;
        item = item->next;
    }
}

// 打印字典内容
void printDictionary(struct Dictionary *dict) {
    for (int i = 0; i < TABLE_SIZE; i++) {
        struct DictItem *item = dict->table[i];
        while (item) {
            printf("Key: %s, Value: %s\n", item->key, item->value);
            item = item->next;
        }
    }
}

// 销毁字典
void destroyDictionary(struct Dictionary *dict) {
    for (int i = 0; i < TABLE_SIZE; i++) {
        struct DictItem *item = dict->table[i];
        while (item) {
            struct DictItem *temp = item;
            item = item->next;
            free(temp->key);
            free(temp->value);
            free(temp);
        }
    }
    free(dict);
}
